package com.atguigu.yygh.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.model.shop.Shop;
import com.atguigu.yygh.shop.repository.ShopRepository;
import com.atguigu.yygh.shop.service.ShopService;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.shop.ShopQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ShopRepository shopRepository;
    @Autowired
    private DictFeignClient dictFeignClient;

    @Override
    public void save(Map<String, Object> paramMap) {
        //把参数map集合转换对象 Shop
        String mapString = JSONObject.toJSONString(paramMap);
        Shop shop = JSONObject.parseObject(mapString, Shop.class);

        //判断是否存在数据
        String shopcode = shop.getShopcode();
        Shop shopExist = shopRepository.getShopByShopcode(shopcode);

        //如果存在，进行修改
        if(shopExist != null) {
            shop.setStatus(shopExist.getStatus());
            shop.setCreateTime(shopExist.getCreateTime());
            shop.setUpdateTime(new Date());
            shop.setIsDeleted(0);
            shopRepository.save(shop);
        } else {//如果不存在，进行添加
            shop.setStatus(0);
            shop.setCreateTime(new Date());
            shop.setUpdateTime(new Date());
            shop.setIsDeleted(0);
            shopRepository.save(shop);
        }
    }

    @Override
    public Shop getByShopCode(String shopcode) {
        Shop shop = shopRepository.getShopByShopcode(shopcode);
        return shop;
    }

    @Override
    public Page<Shop> selectShopPage(Integer page, Integer limit, ShopQueryVo shopQueryVo) {
        //创建pageable对象
        Pageable pageable = PageRequest.of(page - 1, limit);
        Criteria criteria = new Criteria();
        if (!StringUtils.isEmpty(shopQueryVo.getProvinceCode())) {
            criteria.and("provinceCode").is(shopQueryVo.getProvinceCode());
        }
        if (!StringUtils.isEmpty(shopQueryVo.getDistrictCode())) {
            criteria.and("cityCode").is(shopQueryVo.getCityCode());
        }
        if (!StringUtils.isEmpty(shopQueryVo.getDistrictCode())) {
            criteria.and("districtCode").is(shopQueryVo.getDistrictCode());
        }
        if (!StringUtils.isEmpty(shopQueryVo.getShopcode())) {
            criteria.and("shopcode").is(shopQueryVo.getShopcode());
        }
        if (!StringUtils.isEmpty(shopQueryVo.getShopname())) {
            criteria.and("shopname").is(shopQueryVo.getShopname());
        }
        if (!StringUtils.isEmpty(shopQueryVo.getShoptype())) {
            criteria.and("shoptype").is(shopQueryVo.getShoptype());
        }
        if (!StringUtils.isEmpty(shopQueryVo.getStatus())) {
            criteria.and("status").is(shopQueryVo.getStatus());
        }
        Query query = new Query();
        query.addCriteria(criteria);
        query.skip((page - 1) * limit);
        query.limit(limit);
        List<Shop> shops = mongoTemplate.find(query, Shop.class);
        /*
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreNullValues()
                .withIgnoreCase(true);
        //shopSetQueryVo转换Shop对象
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopQueryVo, shop);
        //创建对象
        Example<Shop> example = Example.of(shop, matcher);
        //调用方法实现查询
        Page<Shop> pages = shopRepository.findAll(pageable);*/

        Page<Shop> pages = new PageImpl<>(shops,pageable,limit);
        //获取查询list集合，遍历进行店铺等级封装
        pages.getContent().stream().forEach(item -> {
            this.setShopType(item);
        });
        return pages;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        //根据id查询店铺信息
        Shop shop = shopRepository.findById(id).get();
        //设置修改的值
        shop.setStatus(status);
        shop.setUpdateTime(new Date());
        shopRepository.save(shop);
    }

    @Override
    public Map<String, Object> getShopById(String id) {
        Map<String, Object> result = new HashMap<>();
        Shop shop = this.setShopType(shopRepository.findById(id).get());
        //店铺基本信息（包含店铺等级）
        result.put("shop",shop);
        //单独处理更直观
        result.put("bookingRule", shop.getBookingRule());
        //不需要重复返回
        shop.setBookingRule(null);
        return result;
    }

    @Override
    public String getShopName(String shopcode) {
        Shop shop = shopRepository.getShopByShopcode(shopcode);
        if(shop != null) {
            return shop.getShopname();
        }
        return null;
    }

    @Override
    public List<Shop> findByShopName(String shopname) {
        return shopRepository.findShopByShopnameLike(shopname);
    }

    @Override
    public Map<String, Object> item(String shopcode) {
        Map<String, Object> result = new HashMap<>();
        //店铺详情
        Shop shop = this.setShopType(this.getByShopCode(shopcode));
        result.put("shop", shop);
        //预约规则
        result.put("bookingRule", shop.getBookingRule());
        //不需要重复返回
        shop.setBookingRule(null);
        return result;
    }

    //获取查询list集合，遍历进行店铺等级封装
    private Shop setShopType(Shop shop) {
        //根据dictCode和value获取店铺等级名称
        String shoptypeString = dictFeignClient.getName("Hostype", shop.getShoptype());
        //查询省 市  地区
        String provinceString = dictFeignClient.getName(shop.getProvinceCode());
        String cityString = dictFeignClient.getName(shop.getCityCode());
        String districtString = dictFeignClient.getName(shop.getDistrictCode());

        shop.getParam().put("fullAddress", provinceString + cityString + districtString);
        shop.getParam().put("shoptypeString", shoptypeString);
        return shop;
    }
}
